package cn.zebra.dev.jwt.filter;

import cn.zebra.dev.common.constant.SysConstant;
import cn.zebra.dev.common.restful.Result;
import cn.zebra.dev.common.utils.StrUtils;
import cn.zebra.dev.config.JwtAuthenticationConfigureBean;
import cn.zebra.dev.jwt.utils.JwtTokenUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author runnable@sina.cn
 */
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtAuthenticationConfigureBean configure;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String method = request.getMethod();
        String origin = request.getHeader("Origin");
        String authToken = request.getHeader(configure.getHeader());
        if (StrUtils.isNotBlank(authToken)) {
            String username = JwtTokenUtil.getUserNameFromToken(authToken);
            if (configure.isSso()) {
                response.setHeader("Access-Control-Allow-Origin", origin);
                response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
                response.setHeader("Access-Control-Max-Age", "3600");
                response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
                response.setHeader("Access-Control-Allow-Credentials", "true");
                if ("OPTIONS".equalsIgnoreCase(method)) {
                    response.getOutputStream().write("Success".getBytes(StandardCharsets.UTF_8));
                    return;
                }
                ValueOperations<String, String> operations = redisTemplate.opsForValue();
                String token = operations.get(SysConstant.USER_TOKEN + username);
                if (token == null) {
                    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                    response.setStatus(HttpStatus.FORBIDDEN.value());
                    response.getWriter().write(new ObjectMapper().writeValueAsString(Result.error(403, "您的账号登录信息已过期!请重新登录!")));
                    return;
                }
                if (!token.equalsIgnoreCase(authToken)) {
                    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                    response.setStatus(HttpStatus.FORBIDDEN.value());
                    response.getWriter().write(new ObjectMapper().writeValueAsString(Result.error(403, "您的账号已在其他地方登陆 被迫下线!请重新登录!")));
                    return;
                }
            }
            logger.info(String.format("检查用户名:{%s}", username));
            SecurityContext context = SecurityContextHolder.getContext();
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (JwtTokenUtil.validateToken(authToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                context.setAuthentication(authentication);
                logger.info(String.format("认证用户:{%s}", username));
            }
        }
        chain.doFilter(request, response);
    }
}
